package cn.ywang.pattern.singleton.lazy;

/**
 * 简单的懒汉式单例
 *
 * @author BeatificWang
 * @date 2019/3/10 14:32
 */
public class SimpleLazy {

	private static SimpleLazy INSTANCE;

	/**
	 * 防止反射重复创建，破坏单例
	 */
	private SimpleLazy() {
		if (null != INSTANCE) {
			throw new RuntimeException("不允许重复创建单例");
		}
	}

	/**
	 * 双重锁保障单例，也可以方法添加synchronized，相比来说双重锁性能更优
	 *
	 * @return
	 */
	public static SimpleLazy getInstance() {
		if (null == INSTANCE) {
			synchronized (SimpleLazy.class) {
				if (null == INSTANCE) {
					INSTANCE = new SimpleLazy();
				}
			}
		}
		return INSTANCE;
	}

	/**
	 * 防止反序列化破坏单例
	 *
	 * @return
	 */
	public SimpleLazy readResolve() {
		return INSTANCE;
	}
}
